package com.lap.junit.tools;

import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.params.converter.ArgumentConversionException;
import org.junit.jupiter.params.converter.ArgumentConverter;

import java.util.stream.Stream;

/**
 * 使用方法: '[1,2,3,4]'
 *
 * @author Shuisheng Lao(劳水生)
 * @version 0.0.1
 */
public class IntConverter implements ArgumentConverter {

  @Override
  public Object convert(Object source, ParameterContext context)
      throws ArgumentConversionException {
    if (source instanceof String arg) {
      arg = arg.trim().substring(1, arg.trim().length() - 1).trim();
      if (arg.isEmpty()) return new Integer[] {};

      return Stream.of(arg.split("[,;]"))
          .map(String::trim)
          .map(Integer::valueOf)
          .toArray(Integer[]::new);
    }
    return source;
  }
}
